package com.funmi.lizip.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.entity.ArtificialDisturb;
import com.funmi.lizip.entity.dto.ArtificialDisturb.ArtificialDisturbAddRequest;
import com.funmi.lizip.entity.dto.ArtificialDisturb.ArtificialDisturbQueryRequest;
import com.funmi.lizip.entity.dto.ArtificialDisturb.ArtificialDisturbUpdateRequest;
import com.funmi.lizip.entity.enums.PathEnum;
import com.funmi.lizip.entity.vo.ArtificialDisturbStatisticsVo;
import com.funmi.lizip.entity.vo.ArtificialDisturbVo;
import com.funmi.lizip.service.ArtificialDisturbService;
import com.funmi.lizip.utils.MyJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "人为干扰管理模块")
@RestController
@RequestMapping("/artificialDisturb")
public class ArtificialDisturbController {

    @Autowired
    private ArtificialDisturbService artificialDisturbService;

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "分页获取 人为干扰信息")
    @GetMapping("")
    public R getList(ArtificialDisturbQueryRequest request) throws IllegalAccessException {
        long current = 1;
        long size = 10;
        ArtificialDisturbQueryRequest artificialDisturbQueryRequest = MyJsonUtil.setNullValue(request);
        ArtificialDisturb artificialDisturbQuery = new ArtificialDisturb();
        if (request != null) {
            BeanUtils.copyProperties(artificialDisturbQueryRequest, artificialDisturbQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        QueryWrapper<ArtificialDisturb> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");
        /*if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getTitle())){
            queryWrapper.like("title", request.getTitle());
        }*/
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getType())){
            queryWrapper.like("type", request.getType());
        }
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getFoundWay())){
            queryWrapper.like("found_way", request.getFoundWay());
        }
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getPlace())){
            queryWrapper.like("place", request.getPlace());
        }

        queryWrapper.between("gmt_found",
                (request.getStartTime() == null)? (LocalDateTime.of(2019, 10, 12, 6, 30)): request.getStartTime(),
                (request.getEndTime() == null)? (LocalDateTime.now()):request.getEndTime());

        Page<ArtificialDisturb> artificialDisturbPage = artificialDisturbService.page(new Page<>(current, size), queryWrapper);

        PageDTO<ArtificialDisturbVo> artificialDisturbVoPage = new PageDTO<>(artificialDisturbPage.getCurrent(), artificialDisturbPage.getSize(), artificialDisturbPage.getTotal());
        List<ArtificialDisturbVo> artificialDisturbVoList = artificialDisturbPage.getRecords().stream().map(artificialDisturb -> {
            ArtificialDisturbVo artificialDisturbVo = new ArtificialDisturbVo();
            BeanUtils.copyProperties(artificialDisturb, artificialDisturbVo);
            if (!ObjectUtils.isEmpty(artificialDisturb.getPic())) {
                artificialDisturbVo.setPic("ArtificialDisturb" + "/" + artificialDisturb.getPic());
            }
            return artificialDisturbVo;
        }).collect(Collectors.toList());
        artificialDisturbVoPage.setRecords(artificialDisturbVoList);
        return R.success().data(artificialDisturbVoPage);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "删除 人为干扰信息")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable int id) {
        boolean b = artificialDisturbService.removeById(id);
        if (b) {
            return R.success().message("删除成功");
        }
        return R.success().message("删除失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增 人为干扰信息")
    @PostMapping("")
    public R add(@RequestBody ArtificialDisturbAddRequest request) throws IOException {
        if (request == null) {
            return R.success().data("数据为空");
        }
        ArtificialDisturb artificialDisturb = new ArtificialDisturb();
        BeanUtils.copyProperties(request, artificialDisturb);
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getPic())) {
            LocalDateTime gmtFound = artificialDisturb.getGmtFound();
            String s = "" + gmtFound.getYear() + "-" + gmtFound.getMonthValue() + "-" + gmtFound.getDayOfMonth();
            File dest = new File(PathEnum.PATH.getText() + "\\" + "ArtificialDisturb" + "\\" + s + "\\" + artificialDisturb.getPlace() + "\\" + artificialDisturb.getPic());
            // 将暂存的图片移动到指定文件夹中
            // 文件夹名称
            Path directories = Files.createDirectories(dest.getParentFile().toPath());
            File startFile = new File(PathEnum.PATH.getText() + "\\" + artificialDisturb.getPic());
            boolean b = startFile.renameTo(dest);
            if (!b) {
                R.fail().message("图片保存失败");
            }
            artificialDisturb.setPic(s + "\\" + artificialDisturb.getPlace() + "\\" + artificialDisturb.getPic());
        }

        boolean save = artificialDisturbService.save(artificialDisturb);
        if (save) {
            return R.success().message("新增成功");
        }
        return R.success().message("新增失败");
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "根据id 获取 人为干扰信息")
    @GetMapping("/{id}")
    public R get(@PathVariable int id) {
        ArtificialDisturb artificialDisturb = artificialDisturbService.getById(id);
        if (ObjectUtils.isEmpty(artificialDisturb)){
            return R.fail().message("无数据或被删除");
        }
        ArtificialDisturbVo artificialDisturbVo = new ArtificialDisturbVo();
        BeanUtils.copyProperties(artificialDisturb, artificialDisturbVo);
        if (!ObjectUtils.isEmpty(artificialDisturb.getPic())){
            artificialDisturbVo.setPic("ArtificialDisturb" + "/" + artificialDisturb.getPic());
        }
        return R.success().data(artificialDisturbVo);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改 人为干扰信息内容")
    @PutMapping("")
    public R update(@RequestBody ArtificialDisturbUpdateRequest request) {
        ArtificialDisturb artificialDisturb = new ArtificialDisturb();
        BeanUtils.copyProperties(request, artificialDisturb);
        boolean b = artificialDisturbService.updateById(artificialDisturb);
        if (b) {
            return R.success().message("修改成功");
        }
        return R.fail().message("修改失败");
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "统计 干扰类型 数量")
    @GetMapping("/Statistics")
    public R Statistics() {
        ArtificialDisturbStatisticsVo vo = new ArtificialDisturbStatisticsVo();
        QueryWrapper<ArtificialDisturb> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT type");
        List<ArtificialDisturb> list = artificialDisturbService.list(queryWrapper);
        HashMap<String, Long> map = new HashMap<>();
        list.forEach(artificialDisturbs -> {
            map.put(artificialDisturbs.getType(), artificialDisturbService.count(new QueryWrapper<ArtificialDisturb>().eq("type",artificialDisturbs.getType())));
        });
        vo.setType(map);
        // 从2022年1月份起 至今。统计每月的干扰数量
        LinkedHashMap<String, Long> month = new LinkedHashMap<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime of = LocalDateTime.of(2022, 1, 1, 0, 0);
        for (int j = 0; j < (now.getYear()+1 - of.getYear()); j++) {
            for (int i = of.getMonthValue(); i <= now.getMonthValue(); i++) {
                System.out.println(of.getYear()+"-"+i);
                month.put(of.getYear()+"-"+i,
                        artificialDisturbService.count(new QueryWrapper<ArtificialDisturb>().between("gmt_found"
                                ,LocalDateTime.of(j+of.getYear(), i, 1, 0, 0)
                                , LocalDateTime.of(j+of.getYear(), i,
                                        LocalDateTime.of(j+of.getYear(),i,1,1,1).with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth()
                                        , 23, 59)))
                        );
            }
        }
        vo.setMonths(month);
        return R.success().data(vo);
    }

}
